package com.zf.yichat.service.impl;

import com.zf.yichat.mapper.SysAgreementMapper;
import com.zf.yichat.model.SysAgreement;
import com.zf.yichat.service.AgreementService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

@Service
@Slf4j
public class AgreementServiceImpl implements AgreementService {


    @Autowired
    private SysAgreementMapper agreementMapper;

    @Override
    public void saveAgreement(String type, String content) {
        try {
            String htmlContent = buildHtml(content);

            SysAgreement agreementContent = agreementMapper.queryAgreementByName(type);
            if (null != agreementContent) {
                agreementContent.setContent(htmlContent);
                agreementContent.setUtime(new Date());
                agreementMapper.updateByPrimaryKeySelective(agreementContent);
            }
            else {
                SysAgreement agreement = new SysAgreement();
                agreement.setName(type);
                agreement.setContent(htmlContent);
                agreement.setCtime(new Date());
                agreementMapper.insert(agreement);
            }

        }catch (Exception e) {
            log.error("协议上传失败！", e);
        }
    }



    /**
     * 组装html
     * @param content
     * @return
     */
    public static String buildHtml (String content) {
        StringBuilder sb = new StringBuilder ();
        sb.append ("<!DOCTYPE html>");
        sb.append ("<head>");
        sb.append ("<meta charset=\"UTF-8\">");
        sb.append ("<meta name=\"renderer\"content=\"webkit\">");
        sb.append ("<meta http-equiv=\"X-UA-Compatible\"content=\"IE=edge,chrome=1\">");
        sb.append ("<meta name=\"viewport\"content=\"width=device-width, initial-scale=1, maximum-scale=1\">");
        sb.append ("<title > 用户协议 </title>");
        sb.append ("</head>");
        sb.append ("<body>");
        sb.append (content);
        sb.append ("</body>");
        sb.append ("</html>");
        return sb.toString ();
    }

    /**
     * 存储到本地
     * @param html
     * @param filePath
     */
    public static void saveHtml (String html, String filePath) {
        try {
            // 创建文件夹和文件
            File file = new File (filePath);
            File parentDir = file.getParentFile();
            if (!parentDir.exists()) {
                parentDir.mkdirs();
            }
            file.createNewFile();

            // 写入文件
            PrintWriter pw = new PrintWriter (new FileWriter(file));
            pw.println(html);
            pw.close ();
        } catch (IOException e) {
            e.printStackTrace ();
        }
    }
}
